package com.study.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;

@RestController
public class ProducerController {
    private final JmsMessagingTemplate jmsMessagingTemplate;
    private final Queue queue;
    private final Topic topic;

    @Autowired
    public ProducerController(JmsMessagingTemplate jmsMessagingTemplate, Queue queue, Topic topic) {
        this.jmsMessagingTemplate = jmsMessagingTemplate;
        this.queue = queue;
        this.topic = topic;
    }

    @PostMapping("/queue/test")
    public String sendQueue(@RequestBody String str) {
        for(int i = 0; i < 10; i++) {
            this.sendMessage(this.queue, str + i);
        }
        return "success";
    }

    @PostMapping("/topic/test")
    public String sendTopic(@RequestBody String str) {
        for(int i = 0; i < 10; i++) {
            this.sendMessage(this.topic, str + i);
        }
        return "success";
    }

    /**
     * 发送消息，destination是发送到的队列，message是待发送的消息
     */
    private void sendMessage(Destination destination, final String message){
        jmsMessagingTemplate.convertAndSend(destination, message);
    }
}
